import http from '@/utils/request.js'

// ========================================
// AI 智能问答 API 接口
// ========================================

// 模型配置预设
export const AI_MODELS = {
  // DeepSeek 模型系列
  DEEPSEEK_CHAT: {
    model: 'deepseek-chat',
    deepseekMode: 'chat',
    maxTokens: 1500,
    temperature: 0.7,
    name: 'DeepSeek 对话'
  },
  DEEPSEEK_REASONER: {
    model: 'deepseek-reasoner',
    deepseekMode: 'reasoner',
    maxTokens: 2000,
    temperature: 0.4,
    name: 'DeepSeek 推理'
  },
  
  // 讯飞星火模型系列
  XUNFEI_CHAT: {
    model: 'x1',
    xunfeiVersion: 'v2',
    xunfeiMode: 'chat',
    maxTokens: 1500,
    temperature: 0.7,
    name: '星火 对话'
  },
  XUNFEI_REASONER: {
    model: 'x1',
    xunfeiVersion: 'v2',
    xunfeiMode: 'reasoner',
    maxTokens: 2000,
    temperature: 0.5,
    name: '星火 推理'
  }
}

// ========================================
// 基础AI问答方法
// ========================================

/**
 * 通用AI问答方法
 * @param {Object} params 问答参数
 * @param {string} params.question 问题内容
 * @param {string} params.model 模型类型
 * @param {string} params.sessionId 会话ID（可选）
 * @param {number} params.maxTokens 最大token数
 * @param {number} params.temperature 温度参数
 * @param {string} params.knowledgeBaseId 知识库ID（可选）
 * @param {boolean} params.saveRecord 是否保存记录（默认true）
 * @returns {Promise} 返回AI回答
 */
export const askAI = async (params) => {
  const {
    question,
    model = 'deepseek-chat',
    sessionId,
    maxTokens = 1500,
    temperature = 0.7,
    knowledgeBaseId,
    deepseekMode,
    xunfeiVersion,
    xunfeiMode,
    saveRecord = true
  } = params

  const payload = {
    question,
    model,
    maxTokens,
    temperature,
    saveRecord
  }

  if (sessionId) payload.sessionId = sessionId
  if (knowledgeBaseId) payload.knowledgeBaseId = knowledgeBaseId
  if (deepseekMode) payload.deepseekMode = deepseekMode
  if (xunfeiVersion) payload.xunfeiVersion = xunfeiVersion
  if (xunfeiMode) payload.xunfeiMode = xunfeiMode

  // AI生成接口可能较慢，显式把小程序超时拉长到60s
  return http.post('/qa/generate-answer', payload, { timeout: 60000 })
}

// ========================================
// 便捷AI问答方法
// ========================================

/**
 * DeepSeek 对话模型问答
 * @param {string} question 问题
 * @param {Object} options 选项
 * @returns {Promise} AI回答
 */
export const askDeepSeekChat = async (question, options = {}) => {
  return askAI({
    question,
    ...AI_MODELS.DEEPSEEK_CHAT,
    ...options
  })
}

/**
 * DeepSeek 推理模型问答
 * @param {string} question 问题
 * @param {Object} options 选项
 * @returns {Promise} AI回答
 */
export const askDeepSeekReasoner = async (question, options = {}) => {
  return askAI({
    question,
    ...AI_MODELS.DEEPSEEK_REASONER,
    ...options
  })
}

/**
 * 星火对话模型问答
 * @param {string} question 问题
 * @param {Object} options 选项
 * @returns {Promise} AI回答
 */
export const askXunfeiChat = async (question, options = {}) => {
  return askAI({
    question,
    ...AI_MODELS.XUNFEI_CHAT,
    ...options
  })
}

/**
 * 星火推理模型问答
 * @param {string} question 问题
 * @param {Object} options 选项
 * @returns {Promise} AI回答
 */
export const askXunfeiReasoner = async (question, options = {}) => {
  return askAI({
    question,
    ...AI_MODELS.XUNFEI_REASONER,
    ...options
  })
}

// ========================================
// 会话管理方法
// ========================================

/**
 * 开始新会话
 * @param {string} question 第一个问题
 * @param {Object} modelConfig 模型配置
 * @returns {Promise} 返回会话信息和回答
 */
export const startNewSession = async (question, modelConfig = AI_MODELS.DEEPSEEK_CHAT) => {
  const result = await askAI({
    question,
    ...modelConfig
  })
  
  return {
    sessionId: result.data.sessionId,
    answer: result.data.answer,
    model: modelConfig.name
  }
}

/**
 * 继续会话
 * @param {string} sessionId 会话ID
 * @param {string} question 问题
 * @param {Object} modelConfig 模型配置
 * @returns {Promise} 返回回答
 */
export const continueSession = async (sessionId, question, modelConfig = AI_MODELS.DEEPSEEK_CHAT) => {
  const result = await askAI({
    question,
    sessionId,
    ...modelConfig
  })
  
  return {
    answer: result.data.answer,
    sessionId: result.data.sessionId
  }
}

// ========================================
// 知识库问答方法
// ========================================

/**
 * 基于知识库的AI问答
 * @param {string} question 问题
 * @param {string} knowledgeBaseId 知识库ID
 * @param {Object} modelConfig 模型配置
 * @returns {Promise} AI回答
 */
export const askWithKnowledgeBase = async (question, knowledgeBaseId, modelConfig = AI_MODELS.DEEPSEEK_CHAT) => {
  return askAI({
    question,
    knowledgeBaseId,
    ...modelConfig
  })
}

// ========================================
// 批量问答方法
// ========================================

/**
 * 批量问答
 * @param {Array} questions 问题数组
 * @param {Object} modelConfig 模型配置
 * @param {boolean} useSession 是否使用会话
 * @returns {Promise} 返回所有回答
 */
export const batchAsk = async (questions, modelConfig = AI_MODELS.DEEPSEEK_CHAT, useSession = false) => {
  const results = []
  let sessionId = null

  for (let i = 0; i < questions.length; i++) {
    const question = questions[i]
    
    try {
      let result
      if (useSession && sessionId) {
        result = await continueSession(sessionId, question, modelConfig)
        sessionId = result.sessionId
      } else if (useSession && i === 0) {
        result = await startNewSession(question, modelConfig)
        sessionId = result.sessionId
      } else {
        result = await askAI({
          question,
          ...modelConfig
        })
      }
      
      results.push({
        question,
        answer: result.answer || result.data.answer,
        success: true
      })
    } catch (error) {
      results.push({
        question,
        answer: null,
        error: error.message,
        success: false
      })
    }
  }

  return results
}

// ========================================
// 工具方法
// ========================================

/**
 * 获取模型配置
 * @param {string} modelType 模型类型
 * @returns {Object} 模型配置
 */
export const getModelConfig = (modelType) => {
  return AI_MODELS[modelType] || AI_MODELS.DEEPSEEK_CHAT
}

/**
 * 获取所有可用模型
 * @returns {Array} 模型列表
 */
export const getAvailableModels = () => {
  return Object.keys(AI_MODELS).map(key => ({
    key,
    ...AI_MODELS[key]
  }))
}

/**
 * 检查模型是否支持
 * @param {string} modelType 模型类型
 * @returns {boolean} 是否支持
 */
export const isModelSupported = (modelType) => {
  return Object.keys(AI_MODELS).includes(modelType)
}

// ========================================
// 错误处理方法
// ========================================

/**
 * 处理AI问答错误
 * @param {Error} error 错误对象
 * @returns {Object} 错误信息
 */
export const handleAIError = (error) => {
  let errorMessage = 'AI问答失败'
  let errorType = 'unknown'

  if (error.errMsg) {
    if (error.errMsg.includes('timeout')) {
      errorMessage = '请求超时，请稍后重试'
      errorType = 'timeout'
    } else if (error.errMsg.includes('fail')) {
      errorMessage = '网络连接失败，请检查网络'
      errorType = 'network'
    } else if (error.errMsg.includes('cert')) {
      errorMessage = 'SSL证书错误，请联系管理员'
      errorType = 'ssl'
    }
  } else if (error.message) {
    errorMessage = error.message
  }

  // 后端业务错误增强识别
  const msg = error?.data?.message || error?.message || ''
  if (/AppIdNoAuthError|AppId no auth|no auth/i.test(msg)) {
    errorMessage = '模型厂商鉴权未配置或无权限，请切换为 DeepSeek 或联系管理员配置星火凭据'
    errorType = 'vendor_auth'
  } else if (/xunfei|xf|讯飞|星火/i.test(msg) && /key|secret|appid/i.test(msg)) {
    errorMessage = '星火接口鉴权信息缺失，请联系管理员配置 AppId/ApiKey/ApiSecret'
    errorType = 'vendor_auth'
  }

  return {
    error: true,
    message: errorMessage,
    type: errorType,
    originalError: error
  }
}

// ========================================
// 使用示例
// ========================================

/*
// 基础使用
const answer = await askDeepSeekChat('什么是RAG技术？')

// 推理问答
const reasoningAnswer = await askDeepSeekReasoner('请详细推理RAG的工作原理')

// 星火模型
const xunfeiAnswer = await askXunfeiChat('什么是向量数据库？')

// 会话对话
const session = await startNewSession('你好，我想了解AI技术')
const followUp = await continueSession(session.sessionId, '能详细说说机器学习吗？')

// 知识库问答
const kbAnswer = await askWithKnowledgeBase(
  '什么是RAG？',
  'your-knowledge-base-id'
)

// 批量问答
const batchResults = await batchAsk([
  '什么是AI？',
  '什么是机器学习？',
  '什么是深度学习？'
], AI_MODELS.DEEPSEEK_CHAT, true)
*/ 